package com.novel.controller.system;

import com.novel.common.enums.UserIdentifyEnum;
import com.novel.common.exception.CustomerException;
import com.novel.common.pojo.RedisParamKey;
import com.novel.common.vo.AuthorNovelInfo;
import com.novel.controller.other.BaseController;
import com.novel.pojo.novel.Novel;
import com.novel.pojo.novel.NovelCategory;
import com.novel.pojo.novel.NovelChapter;
import com.novel.pojo.system.User;
import com.novel.service.*;
import com.novel.utils.FileUploadUtil;
import com.novel.utils.GsonTool;
import com.novel.utils.NumFormatUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Controller
@RequestMapping("author")
public class AuthorController extends BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private NovelService novelService;

    @Autowired
    private NovelCommentService commentService;

    @Autowired
    private FileUploadUtil uploadUtil;

    @Autowired
    private NovelChapterService chapterService;

    @Autowired
    private NovelRecommendService novelRecommendService;

    @Autowired
    private NovelRewardService novelRewardService;


    /**
     * 校验用户是否登录并且有登录权限
     */
    public ModelAndView checkPermissionAndLogin(ModelAndView mv, String targetView) {
        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/login");
        } else if (checkUserPermission(UserIdentifyEnum.AUTHOR, user.getIdentify())) {
            mv.setViewName(targetView);
        } else {
            mv.setViewName("redirect:/change/author");
        }
        return mv;
    }

    /**
     * 校验用户是否登录并且有权限
     */
    public boolean checkPermissionAndLogin() {
        User user = getUserInformation();
        if (user == null) {
            throw new CustomerException("用户未登录");
        }
        return checkUserPermission(UserIdentifyEnum.AUTHOR, user.getIdentify());
    }


    /**
     * 更新章节
     */
    @PostMapping("chapter/update")
    @ResponseBody
    public boolean updateChapter(NovelChapter novelChapter) {
        if (checkPermissionAndLogin()) {
            return chapterService.addChapter(novelChapter);
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 删除书籍
     */
    @PostMapping("novel/delete")
    @ResponseBody
    public boolean deleteNovel(String novelId) {
        if (checkPermissionAndLogin()) {
            return novelService.deleteNovel(novelId);
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 新书发布
     */
    @PostMapping("novel/publish")
    public ModelAndView publishNovel(ModelAndView mv, MultipartFile file, Novel novel) throws Exception {
        if (checkPermissionAndLogin()) {
            String imgSrc = "https://www.zuimeng.net/noimg.jpg";
            if (file != null && file.getSize() > 0) {
                imgSrc = uploadUtil.upload(file);
            }
            User user = getUserInformation();
            //封装书籍信息
            novel.setNovelId(UUID.randomUUID().toString());
            novel.setImgSrc(imgSrc);
            novel.setEnd(0);
            novel.setAuthorId(user.getUserId());
            novel.setAuthorName(user.getUserName());
            novel.setNovelClick(0L);
            novel.setRewardAmount(0D);
            novel.setNovelRecommend(0L);
            novel.setCreateTime(new Date());
            novel.setLastTime(new Date());
            novel.setWords(0L);

            novelService.addNovel(novel);

            //设置小说信息
            redisUtils.hashSet(novel.getNovelId(), RedisParamKey.novelInfo, GsonTool.toJson(novel));
            //设置小说点击量
            redisUtils.hashSet(novel.getNovelId(), RedisParamKey.novelClick, novel.getNovelClick() + "");

            mv.setViewName("redirect:/author/novel/list");
            return mv;
        }
        mv.setViewName("redirect:/index");
        return mv;
    }

    /**
     * 小说完本
     */
    @PostMapping("novel/close")
    @ResponseBody
    public boolean closeNovel(String novelId) {
        if (checkPermissionAndLogin()) {
            return novelService.closeNovelByAuthor(novelId, getUserInformation().getUserId());
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 删除评论
     */
    @PostMapping("comment/delete")
    @ResponseBody
    public boolean deletedNovelComment(String id) {
        if (checkPermissionAndLogin()) {
            return commentService.deleteCommentInfoByCommentId(id, getUserInformation());
        }
        throw new CustomerException("权限校验失败!");
    }


    /**
     * 获取作者某本书相关的一些参数
     */
    @PostMapping("param/{id}")
    @ResponseBody
    public AuthorNovelInfo getAuthorParam(@PathVariable("id") String novelId, String authorId) {
        //查询作品总数
        int novelCount = novelService.countNovelByAuthorId(authorId);
        //查询小说总字数
        String wordCount = NumFormatUtils.parseNumber(novelService.findNovelById(novelId).getWords());
        //查询作者头像
        User author = userService.getUserInfo(authorId);

        AuthorNovelInfo authorNovelInfo = AuthorNovelInfo.builder()
                .novelCount(novelCount)
                .wordsCount(wordCount)
                .monthUpdateCount("0天")
                .imgSrc(author.getImgSrc())
                .build();
        return authorNovelInfo;
    }

    /**
     * 根据作者id查询各个小说之间推荐票数量
     */
    @PostMapping("recommend/map")
    @ResponseBody
    public List<Map<String, Object>> getRecommendMap() {
        if (checkPermissionAndLogin()) {
            return novelRecommendService.getRecommendMap(getUserInformation().getUserId());
        }
        throw new CustomerException("权限校验失败!");
    }

    /**
     * 根据作者id查询各个小说之间打赏虚拟币
     */
    @PostMapping("reward/map")
    @ResponseBody
    public List<Map<String, Object>> getRewardMap() {
        if (checkPermissionAndLogin()) {
            return novelRewardService.getRewardMap(getUserInformation().getUserId());
        }
        throw new CustomerException("权限校验失败!");
    }


    /**
     * 跳转到首页
     */
    @GetMapping("index")
    public ModelAndView toIndex(ModelAndView mv) {
        return checkPermissionAndLogin(mv, "/author/author_page");
    }

    /**
     * 跳转到评论管理界面
     */
    @GetMapping("manage/comment")
    public ModelAndView toManageComment(ModelAndView mv,
                                        @RequestParam(required = false, defaultValue = "1") Integer pageNum) {
        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/login");
        } else if (checkUserPermission(UserIdentifyEnum.AUTHOR, user.getIdentify())) {
            mv.setViewName("/author/manage_comment");
            //设置评论内容
            mv.addObject("pageInfo", commentService.queryCommentByAuthor(pageNum, 10, getUserInformation().getUserId()));
        } else {
            mv.setViewName("redirect:/change/author");
        }
        return mv;
    }

    /**
     * 跳转到小说列表页面
     */
    @GetMapping("novel/list")
    public ModelAndView toNovelList(ModelAndView mv,
                                    @RequestParam(required = false, defaultValue = "1") Integer pageNum) {

        User user = getUserInformation();
        if (user == null) {
            mv.setViewName("redirect:/login");
        } else if (checkUserPermission(UserIdentifyEnum.AUTHOR, user.getIdentify())) {
            mv.setViewName("/author/novel_list");
            //设置小说列表信息
            mv.addObject("pageInfo", novelService.findNovelByAuthorId(getUserInformation().getUserId(), pageNum, 10));
        } else {
            mv.setViewName("redirect:/change/author");
        }
        return mv;
    }


    /**
     * 跳转到创建小说页面
     */
    @GetMapping("novel/create")
    public ModelAndView toNovelCreated(ModelAndView mv) {
        checkPermissionAndLogin(mv, "/author/create_novel");
        String categoryStr = redisUtils.stringGet(RedisParamKey.novelCategory);
        mv.addObject("categoryList", GsonTool.fromJsonList(categoryStr, NovelCategory.class));
        return mv;
    }

    /**
     * 跳转到更新页面
     */
    @GetMapping("novel/update")
    public ModelAndView toNovelUpdated(ModelAndView mv,
                                       @RequestParam(required = false) String novelId) {

        checkPermissionAndLogin(mv, "/author/update_chapter");

        List<Novel> novelList = novelService.findNovelByAuthorId(getUserInformation().getUserId());
        if (CollectionUtils.isNotEmpty(novelList)) {
            mv.addObject("novelList", novelList);
        }

        if (StringUtils.isNotBlank(novelId)) {
            mv.addObject("selected", novelId);
        }

        return mv;
    }


}